package com.example.exercise.rule;

import com.example.exercise.common.Pojo;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.Message;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

public class DroolsInitialization {
    /**
     * rule文件路径
     */
    private static final String RULE_FILE_PATH = "src/main/resources/rules/";
    private static final Logger LOGGER = LoggerFactory.getLogger(DroolsInitialization.class);

    public static KieSession getKieSession(String rules) {
        KieServices kieServices = KieServices.Factory.get();
        KieRepository kieRepository = kieServices.getRepository();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        String ruleFileName = RULE_FILE_PATH + UUID.randomUUID().toString().replace("-", "") + ".drl";
        kieFileSystem.write(ruleFileName, rules);
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
            LOGGER.error("创建解析空间异常");
        }
        KieContainer kieContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
        return kieContainer.newKieSession();
//        new KieSessionsPool(50);
    }

    public static <T extends Pojo> String preHandle(T data, String rule) {
        String dateFormat = System.getProperty("drools.dateformat");
        if (dateFormat == null) {
            System.setProperty("drools.dateformat", "yyyy-MM-dd");
        }
        if(!DataInit.fieldExists(data, rule)){
            return null;
        }

        return DataInit.preHandle(data, rule);
    }

}
